<template>
  <div class="app-container">
    <!--    头部搜索区-->
    <el-form v-show="showSearch" ref="queryForm" :model="{childMenus}" size="small" :inline="true" v-if="formDisplay">
      <el-form-item label="菜单名称" prop="menuName">
        <el-input
            v-model="query.name"
            placeholder="请输入菜单名称"
            clearable
            @keyup.enter.native="loadMenu"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="query.status" placeholder="菜单状态">
          <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="loadMenu">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 隐藏按钮 -->
    <el-tooltip content="隐藏" placement="top">
      <el-button icon="el-icon-search" circle @click="hide" class="search-button"></el-button>
    </el-tooltip>

    <!-- 重置按钮 -->
    <el-tooltip content="重置" placement="top">
      <el-button icon="el-icon-refresh" circle @click="resetQuery" class="search-button"></el-button>
    </el-tooltip>


    <!--新增-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAddFirst"
        >新增
        </el-button>
      </el-col>
    </el-row>

    <!-- 表格数据区-->
    <el-table
        v-loading="loading"
        :data="childMenus"
        row-key="menuId"
        :default-expand-all="isExpandAll"
        size="mini"
        :tree-props="{ children: 'childMenu', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="menuName" label="菜单名称" min-width="160"/>

      <el-table-column prop="icon" label="图标" min-width="120">
        <template slot-scope="scope">
          <i :class="scope.row.icon"/>
        </template>
      </el-table-column>

      <el-table-column prop="orderNum" label="排序" min-width="120"/>
      <el-table-column prop="perms" label="权限标识" min-width="120"/>
      <el-table-column prop="component" label="组件路径" min-width="120"/>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <template v-if="scope.row.status === '0'">
            <span type="text">正常</span>
          </template>
          <template v-else>
            <span type="text">停用</span>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="350" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
          >修改
          </el-button>

          <el-button
              size="mini"
              type="text"
              icon="el-icon-plus"
              @click="handleAddSecond(scope.row)"
          >新增
          </el-button>

          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
          >删除
          </el-button>

        </template>
      </el-table-column>
    </el-table>

    <!-----------添加或修改部门对话框 ------------------>
    <!-- 添加菜单对话框 -->
    <el-dialog title="添加菜单" :visible.sync="dialogFormVisible" width="680px" append-to-body>
      <el-form :rules="promptBox" ref="promptBox" :model="childMenu" size="small">
        <!-- 第一列 -->
        <el-row>
          <el-col :span="30">
            <el-form-item label="上级菜单" label-width="80px">
              <Treeselect
                  v-model="childMenu.parentId"
                  :options="mainCategory"
                  :placeholder="'请选择人员'"
                  :normalizer="normalizer"
                  :multiple="false"
                  :disable-branch-nodes="false"
                  search-nested
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二列 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="菜单类型" label-width="80px">
              <el-radio-group v-model="childMenu.menuType">
                <el-radio :label="'M'">目录</el-radio>
                <el-radio :label="'C'">菜单</el-radio>
                <el-radio :label="'F'">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三列 -->
        <el-form-item label="菜单图标" label-width="80px">
          <div class="chooseIcons">
            <el-popover placement="top-start" :append-to-body="false" width="30vw" trigger="click">
              <div slot="reference" class="iconDiv">
                <i :class="userChooseIcon || childMenu.icon"/>
                <div class="iconName">{{ chooseIcons }}</div>
              </div>
              <div class="iconList">
                <i
                    v-for="item in iconList"
                    :key="item"
                    :class="[item, 'icon']"
                    style="font-size: 20px"
                    @click="setIcon(item)"
                />
              </div>
            </el-popover>
          </div>
        </el-form-item>

        <!--第四列-->
        <el-row>
          <el-col :span="12">
            <el-form-item label="菜单名称" label-width="80px" prop="menuName">
              <el-input v-model="childMenu.menuName" placeholder="请输入菜单名称"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="显示排序" label-width="80px" prop="orderNum">
              <el-input-number
                  v-model="childMenu.orderNum"
                  controls-position="right"
                  :min="1"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!--第五列-->
        <el-row v-if="childMenu.menuType !== 'F'">
          <el-col :span="12">
            <el-form-item label="是否外联" label-width="80px">
              <el-radio-group v-model="childMenu.isFrame">
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="路由地址" label-width="80px" prop="path">
              <el-input v-model="childMenu.path" placeholder="monitor"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!--第六列-->
        <el-row>
          <el-col v-if="childMenu.menuType !== 'M' && childMenu.menuType !== 'F'" :span="12">
            <el-form-item label="主键路径" label-width="80px">
              <el-input v-model="childMenu.component" placeholder="请输入主键路径"/>
            </el-form-item>
          </el-col>
          <el-col v-if="childMenu.menuType !== 'M'" :span="12 ">
            <el-form-item label="权限标识" label-width="80px">
              <el-input v-model="childMenu.perms" placeholder="请输入权限标识"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!--第七列-->
        <el-row>
          <el-col v-if="childMenu.menuType !== 'F'" :span="12">
            <el-form-item label="显示状态" label-width="80px">
              <el-radio-group v-model="childMenu.visible">
                <el-radio :label="'0'">是</el-radio>
                <el-radio :label="'1'">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col v-if="childMenu.menuType !== 'F'" :span="12">
            <el-form-item label="菜单状态" label-width="80px">
              <el-radio-group v-model="childMenu.status">
                <el-radio :label="'0'">正常</el-radio>
                <el-radio :label="'1'">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!--第8列-->
        <el-row v-if="childMenu.menuType !== 'M' && childMenu.menuType !== 'F'">
          <el-col :span="24">
            <el-form-item label="是否缓存" label-width="80px">
              <el-radio-group v-model="childMenu.isCache">
                <el-radio :label="0">正常</el-radio>
                <el-radio :label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <!--确认取消-->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--修改菜单对话框-->
    <el-dialog title="修改菜单" :visible.sync="dialogFormVisible2" width="680px" append-to-body>
      <el-form :rules="promptBox" ref="promptBox" :model="childMenu" size="small">
        <!-- 第一列 -->
        <el-row>
          <el-col :span="30">
            <el-form-item label="上级菜单" label-width="80px">
              <Treeselect
                  v-model="childMenu.menuId"
                  :options="mainCategory"
                  :placeholder="'请选择人员'"
                  :normalizer="normalizer"
                  :multiple="false"
                  :disable-branch-nodes="false"
                  search-nested
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二列 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="菜单类型" label-width="80px">
              <el-radio-group v-model="childMenu.menuType">
                <el-radio :label="'M'">目录</el-radio>
                <el-radio :label="'C'">菜单</el-radio>
                <el-radio :label="'F'">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三列 -->
        <el-form-item label="菜单图标" label-width="80px">
          <div class="chooseIcons">
            <el-popover placement="top-start" :append-to-body="false" width="30vw" trigger="click">
              <div slot="reference" class="iconDiv">
                <i :class="userChooseIcon || childMenu.icon"/>
                <div class="iconName">{{ chooseIcons }}</div>
              </div>
              <div class="iconList">
                <i
                    v-for="item in iconList"
                    :key="item"
                    :class="[item, 'icon']"
                    style="font-size: 20px"
                    @click="setIcon(item)"
                />
              </div>
            </el-popover>
          </div>
        </el-form-item>

        <!--第四列-->
        <el-row>
          <el-col :span="12">
            <el-form-item label="菜单名称" label-width="80px" prop="menuName">
              <el-input v-model="childMenu.menuName" placeholder="请输入菜单名称"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="显示排序" label-width="80px" prop="orderNum">
              <el-input-number
                  v-model="childMenu.orderNum"
                  controls-position="right"
                  :min="1"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!--第五列-->
        <el-row v-if="childMenu.menuType !== 'F'">
          <el-col :span="12">
            <el-form-item label="是否外联" label-width="80px">
              <el-radio-group v-model="childMenu.isFrame">
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="路由地址" label-width="80px" prop="path">
              <el-input v-model="childMenu.path" placeholder="monitor"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!--第六列-->
        <el-row>
          <el-col v-if="childMenu.menuType !== 'M' && childMenu.menuType !== 'F'" :span="12">
            <el-form-item label="主键路径" label-width="80px">
              <el-input v-model="childMenu.component" placeholder="请输入主键路径"/>
            </el-form-item>
          </el-col>
          <el-col v-if="childMenu.menuType !== 'M'" :span="12 ">
            <el-form-item label="权限标识" label-width="80px">
              <el-input v-model="childMenu.perms" placeholder="请输入权限标识"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!--第七列-->
        <el-row>
          <el-col v-if="childMenu.menuType !== 'F'" :span="12">
            <el-form-item label="显示状态" label-width="80px">
              <el-radio-group v-model="childMenu.visible">
                <el-radio :label="'0'">是</el-radio>
                <el-radio :label="'1'">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col v-if="childMenu.menuType !== 'F'" :span="12">
            <el-form-item label="菜单状态" label-width="80px">
              <el-radio-group v-model="childMenu.status">
                <el-radio :label="'0'">正常</el-radio>
                <el-radio :label="'1'">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!--第8列-->
        <el-row v-if="childMenu.menuType !== 'M' && childMenu.menuType !== 'F'">
          <el-col :span="24">
            <el-form-item label="是否缓存" label-width="80px">
              <el-radio-group v-model="childMenu.isCache">
                <el-radio :label="0">正常</el-radio>
                <el-radio :label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <!--确认取消-->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {elementIcons} from '@/assets/icon/icon'

export default {
  components: {Treeselect},
  data() {
    return {
      //弹出层输入框提示
      promptBox: {
        menuName: [{required: true, message: '菜单名称不能为空', trigger: 'blur'}],
        orderNum: [{
          required: true,
          message: '菜单顺序不能为空',
          trigger: 'blur'
        }],
        path: [{
          required: true,
          message: '路由地址不能为空',
          trigger: 'blur'
        }]
      },
      // 控住条件框显示和隐藏
      formDisplay: true,
      // 图标
      userChooseIcon: '',
      chooseIcons: '',
      iconList: [],
      // 头部搜索条件
      query: {
        name: '',
        status: ''
      },
      // Menu字段
      childMenu: {
        'menuId': null,
        'menuName': '',
        'parentId': '',
        'orderNum': '',
        'path': '',
        'component': '',
        'isFrame': '',
        'isCache': '',
        'menuType': '',
        'visible': '',
        'status': '',
        'perms': '',
        'icon': '',
        'createBy': '',
        'createTime': '',
        'updateBy': '',
        'updateTime': '',
        'remark': ''
      },
      // 显示搜索条件
      showSearch: true,
      // 树的数据
      childMenus: [],
      // 加了主类目的树
      mainCategory: [],
      // 遮罩层
      loading: false,
      // 是否展开，默认全部展开
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 显示、停用
      statusOptions: [
        {
          value: '0',
          label: '正常'
        },
        {
          value: '1',
          label: '停用'
        }],
      // 弹框状态
      dialogFormVisible: false,
      dialogFormVisible2: false,
      // 弹框的样式参数
      formLabelWidth: '120px',
      //   回填用的id
      backfillingId: ''
    }
  },
  methods: {
    // 折叠隐藏查询框
    hide() {
      this.formDisplay = !this.formDisplay
    },
    // 给icon绑定的点击事件
    setIcon(icon) {
      console.log(icon)
      // 将i的样式设为选中的样式el-icon-xxx
      this.userChooseIcon = icon
      this.chooseIcons = ''
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      // 去掉children=[]的children属性
      if (node.childMenu && !node.childMenu.length || node.childMenu == null) {
        delete node.childMenu
      }
      return {
        id: node.menuId,
        label: node.menuName,
        children: node.childMenu
      }
    },
    // 实现界面渲染
    loadMenu() {
      this.$axios.get('/sysMenu/findMenuTree?menuName=' + encodeURIComponent(this.query.name) + '&status=' + encodeURIComponent(this.query.status
      ))
          .then(result => {
            if (result.data.data) {
              this.childMenus = result.data.data
              console.log("主界面")
              console.log(this.childMenus)
            }
          })
          .finally(() => {
            this.loading = false
          })
    },
    //   时间解析器
    parseTime(time, pattern) {
      if (!time) return null
      const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
      const date = typeof time === 'object' ? time : new Date(time)
      const formatObj = {
        y: date.getFullYear(),
        m: (date.getMonth() + 1).toString().padStart(2, '0'),
        d: date.getDate().toString().padStart(2, '0'),
        h: date.getHours().toString().padStart(2, '0'),
        i: date.getMinutes().toString().padStart(2, '0'),
        s: date.getSeconds().toString().padStart(2, '0'),
        a: date.getDay()
      }
      const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        if (key === 'a') return ['日', '一', '二', '三', '四', '五', '六'][formatObj[key]]
        return formatObj[key] || 0
      })
      return time_str
    },

    // 新增和修改的时候都会重新查询一遍树
    newAddAndModify() {
      this.$axios.get('/sysMenu/findMenuTreeMainCategory')
          .then(result => {
            if (result.data.data) {
              this.mainCategory = JSON.parse(JSON.stringify(result.data.data))
            }
          })
    },
    // 第一个新增
    handleAddFirst() {
      this.newAddAndModify();
      this.resetChildMenu();
      // 直接回显主类目
      this.childMenu.parentId = '0'; // 或者设置成主类目的id
      this.childMenu.menuType = 'M'; // 假设是目录
      this.childMenu.isFrame = 0; // 示例：是否外联，默认是
      this.childMenu.visible = '0'; // 示例：显示状态，默认是
      this.childMenu.status = '0'; // 示例：菜单状态，默认正常
      // 清除表单验证状态和样式
      this.$nextTick(() => {
        this.$refs.promptBox.clearValidate();
      });
      // 打开对话框
      this.dialogFormVisible = true;
    },
    // 第二个新增效果
    handleAddSecond(role) {
      this.newAddAndModify()
      this.resetChildMenu()
      this.childMenu.parentId = JSON.parse(JSON.stringify(role.menuId));
      this.childMenu.menuType = 'M'; // 假设是目录
      this.childMenu.isFrame = 0; // 示例：是否外联，默认是
      this.childMenu.visible = '0'; // 示例：显示状态，默认是
      this.childMenu.status = '0'; // 示例：菜单状态，默认正常
      // 清除表单验证状态和样式
      this.$nextTick(() => {
        this.$refs.promptBox.clearValidate();
      });
      // 打开对话框
      this.dialogFormVisible = true
    },
    // 修改
    handleUpdate(role) {
      this.newAddAndModify()
      this.backfillingId = role.menuId
      this.childMenu = JSON.parse(JSON.stringify(role))
      this.childMenu.menuId = JSON.parse(JSON.stringify(role.parentId));
      // 清除表单验证状态和样式
      this.$nextTick(() => {
        this.$refs.promptBox.clearValidate();
      });
      this.dialogFormVisible2 = true;
    },
    // 删除
    handleDelete(rowData) {
      const postId = rowData.menuId; // 获取岗位编码

      this.$confirm(`确定删除岗位编码为 ${postId} 的岗位吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (rowData.childMenu && rowData.childMenu.length > 0) {
          // 有子目录，禁止删除
          this.$message.warning('该菜单有子目录，无法删除');
          return;
        }
        this.$axios.delete('/sysMenu/delMenu/' + postId)
            .then(result => {
              if (result.data.data) {
                this.loadMenu()
              }
            })
      }).catch(() => {
        // 用户点击取消的处理逻辑
      });
    },
// 提交表单
    submitForm() {
      if (this.$refs.promptBox && this.$refs.promptBox.validate) {
        // 如果 promptBox 存在且需要验证，则执行验证
        this.$refs.promptBox.validate(valid => {
          if (valid) {
            // 验证通过，执行提交操作
            if (this.dialogFormVisible2) {
              this.confirmOk2();
            } else {
              this.confirmOk();
            }
          }
        });
      } else {
        // 如果 promptBox 不存在或不需要验证，直接执行提交操作
        if (this.dialogFormVisible2) {
          this.confirmOk2();
        } else {
          this.confirmOk();
        }
      }
    },
    confirmOk2() {
      this.childMenu.menuId = this.backfillingId
      this.$axios.put('/sysMenu/updateMenu', this.childMenu)
          .then(result => {
            if (result.data.data) {
              this.loadMenu()
              location.reload();
            }
          })
      this.dialogFormVisible2 = false
    },
    // 确定
    confirmOk() {
      this.$axios.post('/sysMenu/addMenu', this.childMenu)
          .then(result => {
            console.log(this.childMenu)
            if (result.data.data) {
              this.loadMenu()
            }
          })
      this.dialogFormVisible = false
    },
    // 重置resetChildMenu 方法
    resetChildMenu() {
      this.childMenu = JSON.parse(JSON.stringify({
        'menuId': null,
        'menuName': '',
        'parentId': '',
        'orderNum': '',
        'path': '',
        'component': '',
        'isFrame': '',
        'isCache': '',
        'menuType': '',
        'visible': '',
        'status': '',
        'perms': '',
        'icon': '',
        'createBy': '',
        'createTime': '',
        'updateBy': '',
        'updateTime': '',
        'remark': ''
      }));
      // 清除表单验证状态和样式
      this.$nextTick(() => {
        this.$refs.promptBox.clearValidate();
      });
    },
    // 表单重置
    resetQuery() {
      this.query = {name: '', status: ''}
      this.loadMenu()
    },
    //   取消
    cancel() {
      this.resetChildMenu()
      this.dialogFormVisible = false
      this.dialogFormVisible2 = false
    }
  },
  mounted() {
    this.iconList = elementIcons
    this.loading = true
    this.loadMenu()
  }
}

</script>

<style>
.chooseIcons {
  width: 100%;
}

.iconList {
  width: 30vw;
  height: 300px;
  overflow-y: scroll;
  overflow-x: hidden;
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
}

.icon {
  display: inline-block;
  width: 60px;
  height: 45px;
  color: #000000;
  font-size: 20px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  cursor: pointer;
  text-align: center;
  line-height: 45px;
  margin: 5px;

}

.icon:hover {
  color: red;
  border-color: red;
}

.iconDiv {
  width: 100%;
  height: 50%;

  display: flex;
  flex-direction: row;
  align-items: center;
}

.iconName {
  width: 50%;
  height: 32px;
}

.el-icon-phone-outline ::v-deep {
  position: absolute;
  left: 10px;
}
</style>
